//
//  AddressModel.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/25.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import HandyJSON

struct AddressModel: HandyJSON {
    var name: String = ""
    var id: String = ""
}

struct AddressInfoModel: HandyJSON {
    // 省
    var provinceName = ""
    var provinceId = ""
    
    // 市
    var cityName = ""
    var cityId = ""
    
    // 区
    var areaName = ""
    var areaId = ""
}

extension AddressModel {
    /// 获取所有省
    static func getProvinceList(success: @escaping (_ models: [AddressModel]) -> Void,
                                failure: @escaping (_ errorMsg: String?) -> Void) {
        HttpTool.shared.request(target: ApiManager.provinceList, success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let models = JSONDeserializer<AddressModel>.deserializeModelArrayFrom(json: json["data"].description) as? [AddressModel] {
                    success(models)
                } else {
                    failure("请求数据发生错误，稍后重试")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
    
    /// 根据省id获取城市
    static func getCityList(provinceId: String, success: @escaping (_ models: [AddressModel]) -> Void, failure: @escaping (_ errorMsg: String?) -> Void) {
        let paras = ["id": provinceId]
        HttpTool.shared.request(target: ApiManager.cityList(paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let models = JSONDeserializer<AddressModel>.deserializeModelArrayFrom(json: json["data"].description) as? [AddressModel] {
                    success(models)
                } else {
                    failure("请求数据发生错误，稍后重试")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
    
    /// 根据城市id获取区
    static func getAreaList(cityId: String, success: @escaping (_ models: [AddressModel]) -> Void, failure: @escaping (_ errorMsg: String?) -> Void) {
        let paras = ["id": cityId]
        HttpTool.shared.request(target: ApiManager.areaList(paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let models = JSONDeserializer<AddressModel>.deserializeModelArrayFrom(json: json["data"].description) as? [AddressModel] {
                    success(models)
                } else {
                    failure("请求数据发生错误，稍后重试")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
}
